/* $RCSFile: DocumentsView.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Documents/DocumentsView.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:53  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Configuration;
using AddonNice.UI;
using AddonNice.Diagnostics;
using AddonNice.Settings.PageModules.Documents;

using AddonNice.CRMWrapper;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Documents
{
	public partial class DocumentsView :  StdAuxPage // ADNPage
	{
        public override bool FastLoadPage
        {
            get
            {
                return true;
            }
        }

        /// <summary>
		/// Builds simplified HTML head element 
		/// </summary>
		protected override void BuildHtmlHead()
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DocumentsView BuildHtmlHead BEG.",PageTraceSwitch.Sw.Info);
            
            //Addon Nice is the generator
            HtmlMeta hm         =   new HtmlMeta();
            hm.Name             =   "generator";
            hm.Content          =   "AddonNice - http://www.addonnice.com";
            Header.Controls.Add(hm);
		}

        protected override void OnLoad(EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DocumentsView OnLoad BEG RawUrl: {0}",Request.RawUrl),PageTraceSwitch.Sw.Info);
            base.OnLoad(e);
        }


        /// <summary>
		/// The Page_Load event handler on this Page is used to
		/// obtain obtain the contents of a document from the 
		/// Documents table, construct an HTTP Response of the
		/// correct type for the document, and then stream the 
		/// document contents to the response.  It uses the 
		/// AddonNice.DocumentDB() data component to encapsulate 
		/// the data access functionality.
		/// </summary>
		protected void Page_Load(object sender, System.EventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DocumentsView Page_Load  isNewItem: {0}",isNewItem),PageTraceSwitch.Sw.Info);
		    if ( !isNewItem ) 
		    {
		        SqlDataReader dBContent     =	null;
			    try
			    {
			        if ( !isCrmItem ) 
			        {
				        // Obtain Document Data from Documents table
				        dBContent			    =	new DocumentDB().GetDocumentContentGlobalized(ItemID);

				        if ( dBContent.Read() )
				        {
					        // Serve up the file by name
					        Response.AppendHeader("content-disposition", "filename=" + (string)dBContent["FileName"]);          
                
					        // set the content type for the Response to that of the 
					        // document to display.  For example. "application/msword"
					        // Change for translate extension-files to exact contentType
					        // Response.ContentType = (string) dBContent["ContentType"];
					        Response.ContentType = giveMeContentType((string) dBContent["ContentType"]);
                
					        // output the actual document contents to the response output stream
					        Response.OutputStream.Write((byte[]) dBContent["Content"], 0, (int) dBContent["ContentSize"]);
					        // end the response
					        Response.End();
			            }
			        }
                    else
                    {
                        ADNDynSalesliteratureitem s =   new ADNDynSalesliteratureitem(Wrapper,ItemCrmID);
                        s.Retrieve();
                        bool isOk                   =   false;
                        bool useNewAPI              =   moduleSettingsDic[DStr.DOCUMENTS_NEWAPI].ToBool();
                        byte[] content              =   ( useNewAPI ) ? s.DownloadAttachment2(false,string.Empty):s.DownloadAttachment(false,string.Empty, ref isOk);
				        Response.AppendHeader("content-disposition", "filename=" + s.filename);          
				        Response.ContentType        =   s.mimetype;
				        Response.OutputStream.Write(content, 0, s.filesize);
				        Response.End();
                    }
			    }
			    catch(Exception ex)
			    {
                    if ( PageTraceSwitch.Sw.TraceError )
				        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentsView Page_Load  ex : {0}",ex),PageTraceSwitch.Sw.Info);
                    throw;
			    }
			    finally
			    {
				    if ( dBContent != null )
					    dBContent.Close();
			    }
		    }
		}

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add ("F9645B82-CB45-4C4C-BB2D-72FA42FE2B75");
				return al;
			}
		}

		/// <summary>
		/// Return the contentType for a especific extension
		/// </summary>
		public static string giveMeContentType (string extension) 
		{
            return ADNDynEmail.MimeTypeFromExt(extension.ToLower());
		}

		#region Std Overrides

        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent() 
		{
			Load += new EventHandler(Page_Load);
		}

		#endregion Std Overrides

	}

}
